package com.bysj.agent.controller;

import bean.ChatMessage;
import com.bysj.agent.assistant.Assistant;
import com.bysj.agent.assistant.SystemAssistant;
import com.bysj.agent.assistant.UserAssistant;
import com.bysj.agent.bean.ChatForm;
import com.bysj.agent.feign.TokenService;

import com.bysj.agent.rag.DynamicContentRetriever;
import com.bysj.agent.service.ImageAnalysisService;
import com.bysj.agent.service.MessageService;
import com.bysj.agent.service.RagService;
import com.bysj.agent.service.WebSearchService;
import com.bysj.agent.tools.UserTools;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.service.AiServices;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "二手客服")
@RestController
@RequestMapping("/agent")
@Slf4j
public class AgentController {
    @Autowired
    private Assistant assistant;

    @Autowired
    private SystemAssistant systemAssistant;

    @Autowired
    private OpenAiChatModel openAiChatModel;

    @Autowired
    private ChatMemoryProvider chatMemoryProvider;

    @Autowired
    private UserTools userTools;


    @Autowired
    private RagService ragService;

    @Autowired
    private ImageAnalysisService imageAnalysisService;

    @Autowired
    private WebSearchService webSearchService;

    @PostMapping("/chat")
    public String chat(@RequestBody ChatForm chatForm){
        return assistant.chat(chatForm.getMemoryId(),chatForm.getMessage());
    }

    @PostMapping("/user/chat")
    public String userChat(@RequestBody ChatMessage chatmessage) throws Exception{
        log.info("调用");
        try{
            MessageService.setMessage(chatmessage);

            String urls = ragService.getDocs(chatmessage.getProductId());

            System.out.println("\n\n\n\n");
            System.out.println("usrls:");
            System.out.println(urls);

            DynamicContentRetriever dynamicContentRetriever = new DynamicContentRetriever(urls);

            ContentRetriever contentRetriever = dynamicContentRetriever.contentRetriever();

            UserAssistant userAssistant = AiServices.builder(UserAssistant.class)
                    .chatLanguageModel(openAiChatModel)
                    .chatMemoryProvider(chatMemoryProvider)
                    .tools(userTools)
                    .contentRetriever(contentRetriever)
                    .build();
            StringBuffer  content = new StringBuffer();
            if(chatmessage.getImageAnalysis()!=null){
                content.append("图片描述是:").append( chatmessage.getImageAnalysis());
            }
            if(chatmessage.getIsWebSearch().equals("1")){
                String webSearch = webSearchService.search(chatmessage.getContent());
                content.append("对于用户的消息进行搜索结果是:").append(webSearch);
            }

            content.append("用户的消息是").append(chatmessage.getContent());
            String chat = userAssistant.chat(Long.valueOf(chatmessage.getChatListId()),content.toString());
            return chat;
        }finally {
            MessageService.clearMessage();
        }
    }


    @PostMapping("/system/chat")
    public String systemChat(@RequestBody ChatMessage chatmessage){
        try {
            // 设置message到ThreadLocal
            MessageService.setMessage(chatmessage);
            return systemAssistant.chat(Long.valueOf(chatmessage.getChatListId()),chatmessage.getContent());
        } finally {
            // 确保清理ThreadLocal，防止内存泄漏
            MessageService.clearMessage();
        }
    }

    @PostMapping("/image")
    public String image(@RequestParam("file") MultipartFile image){
        System.out.println("图片解析被调用");
        String analysis = imageAnalysisService.analysisImage(image);
        System.out.println("解析结果是");
        System.out.println(analysis);
        return analysis;
    }
}
